package com.nju.edu.android_app.callback;

import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.R.bool;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

import com.nju.edu.android_app.MainActivity;
import com.nju.edu.android_app.StreamAdapter;
import com.nju.edu.android_app.StreamItem;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.demo.R;
import com.weibo.sdk.android.net.RequestListener;

public class GetWeiBoListener implements RequestListener {

	private MainActivity mainActivity;

	public GetWeiBoListener(MainActivity mainActivity) {
		this.mainActivity = mainActivity;
	}

	@Override
	public void onComplete(String response) {
		boolean found = false;
		try {
			System.out.println("开始处理");
			JSONTokener jsonTokener = new JSONTokener(response);
			JSONObject status = (JSONObject) jsonTokener.nextValue();
			JSONArray array = status.getJSONArray("statuses");
			for (int i = MainActivity.num_weibo_toget - 1; i >= 0; i--) {
				JSONObject weibo = (JSONObject) array.get(i);
				long id = weibo.getLong("id");
				if (id > MainActivity.maxid) {
					found = true;
					Message msg = new Message();
					Bundle bundle = new Bundle();
					bundle.putString("text", weibo.getString("text"));
					JSONObject user = (JSONObject) weibo.get("user");
					if(weibo.has("thumbnail_pic"))
						bundle.putString("pic_url",
								weibo.getString("thumbnail_pic"));
					bundle.putString("url", user.getString("profile_image_url"));
					bundle.putString("name", user.getString("name"));
					bundle.putString("source", weibo.getString("source"));
					bundle.putLong("id", id);
					msg.setData(bundle);
					msg.what = 1;
					mainActivity.handler.sendMessage(msg);
					MainActivity.maxid = id;
				}
			}
			System.out.println("处理完毕");
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally
		{
		if (!found) {
			Message msg = new Message();
			msg.what = 0;
			mainActivity.handler.sendMessage(msg);
		}
		}
	}

	@Override
	public void onIOException(IOException e) {
		// TODO Auto-generated method stub
		System.out.println(e);
	}

	@Override
	public void onError(WeiboException e) {
		// TODO Auto-generated method stub
		System.out.println(e);
	}
}
